﻿using CK.Sprite.CrossCutting;
using CK.Sprite.Framework;
using CK.Sprite.Interceptor;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Interceptor
{
    public class FormInterceptor : AbpInterceptor, ITransientDependency
    {
        private readonly IHttpContextAccessor _httpContextAccessor; // notice: Services.AddHttpContextAccessor();
        private readonly IFormViewValidator _formViewValidator; // notice: Services.AddHttpContextAccessor();
        private readonly ILogger<FormInterceptor> _logger;

        public FormInterceptor(IHttpContextAccessor httpContextAccessor, ILogger<FormInterceptor> logger, IFormViewValidator formViewValidator)
        {
            _httpContextAccessor = httpContextAccessor;
            _logger = logger;
            _formViewValidator = formViewValidator;
        }

        public override async Task InterceptAsync(IAbpMethodInvocation invocation)
        {
            // todo: 将方法所在的表单Id和视图Id及对应的版本号添加到Header中，验证是否过期，过期则直接返回，提示用户刷新表单
            if (_httpContextAccessor != null && _httpContextAccessor.HttpContext != null && _httpContextAccessor.HttpContext.Request.Headers.ContainsKey(SpriteConst.FormValidateRequestHeader)) // 包含微信请求Token，验证Token
            {
                var isValidate = _formViewValidator.CheckIsLastVersion(_httpContextAccessor.HttpContext.Request.Headers[SpriteConst.FormValidateRequestHeader].ToString());
                if (!isValidate)
                {
                    throw new SpriteException("页面已经更新，请手动刷新页面或点击页面刷新按钮刷新页面！");
                }
            }

            await invocation.ProceedAsync();
        }
    }
}
